<%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@include file="../WEB-INF/jspf/controlesessao.jspf"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Nova Turma</title>
        <script type="text/javascript" src="../js/jquery.js" ></script>
        <script type="text/javascript" src="../js/jquery-ui-1.8.2.custom.min.js" ></script>
        <script type="text/javascript" src="../js/jquery.ui.datepicker-pt-BR.js" ></script>
        <link rel="stylesheet" type="text/css" media="screen" href="../css/ui.jqgrid.css" />
        <script src="../js/i18n/grid.locale-pt-br.js" type="text/javascript"></script>
        <script src="../js/jquery.jqGrid.src.js" type="text/javascript"></script>
        <script type="text/javascript" src="../js/jquery.validate.js"></script>
        <script type="text/javascript" src="../js/forms.js"></script>
        <script type="text/javascript" src="../js/alocacao.js"></script>
        <link rel="stylesheet" href="../css/forms.css">
        <link rel="stylesheet" href="../css/ui-lightness/jquery-ui-1.8.2.custom.css">
    </head>
    <script>
        $(document).ready(function(){
            $("#form").validate({
                rules: {
                    matricula: {required: true}
                    ,id_turno: {required: true,digits: true
                    }
                    ,data_inicio: {required: true,date: true
                    }
                    ,data_fim: {required: true,date: true
                    }
                },
                submitHandler: function(form) {
                    salvar(form);
                }
            });

            $("#estruturar").click(function(){
                $("#operacao").val("estruturar");
            });

            $("#ordenar").click(function(){
                $("#operacao").val("ordenar");
            });
        });


        $(function() {
            $('#data_inicio').datepicker();
            // getHorariosTurno();
            $("#msg").dialog('destroy');

            $("#msg").attr("title", "sgd - Mensagem");
            $("#msg").dialog({
                autoOpen:false,
                resizable: true,
                height: 240,
                width:440,
                modal: true
            });

            $("#id_modulo").change(function(){
                $("#reservas").load('fm_getReservas.jsp', {'id_turma':$("#id_turma").val(),'id_modulo':$(this).val()});
            });

            $("#link_horarios").click(function()
            {

                $("#horarios").fadeToggle("slow", "linear");

            });

            $("#link_horarios").click();
        });

    </script>


    <body>
        <div id="formulario">
            <form name="form" id="form" method="post" action="update.jsp" >
                <input type="hidden" id="operacao" name="operacao" value="">
                <div id="formulario">
                    <fieldset><legend>Dados</legend>
                        <sql:query var="query" dataSource="jdbc/dbo_MicrosoftSQLServer">
                            SELECT  * FROM Turmas
                            where id_turma=?
                            <sql:param value="${param.chave}"/>
                        </sql:query>
                        <c:forEach var="row" items="${query.rows}">
                            <label>Código da Turma: ${row.id_turma}</label>
                            <p><label class="lbInput">Tipo<em>*</em></label>
                                <sql:query var="queryTipo" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    SELECT  *
                                    FROM tipoturma
                                    order by desc_tipoturma
                                </sql:query>
                                <select name="id_tipoturma" disabled>
                                    <option value="">Selecione uma opção</option>
                                    <c:forEach var="rowTipo" items="${queryTipo.rows}">
                                        <option value="${rowTipo.id_tipoturma}" ${rowTipo.id_tipoturma==row.id_tipoturma?'selected':''}>${rowTipo.desc_tipoturma}</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <input name="id_turma" id="id_turma" value="${row.id_turma}" type="hidden">
                            <p><label class="lbInput">Curso<em>*</em></label>
                                <sql:query var="queryCursos" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    SELECT  Cursos.*
                                    FROM Cursos
                                    order by nome_curso, versao_curso
                                </sql:query>
                                <select name="id_curso" class="required" disabled >
                                    <option value="">Selecione um curso</option>
                                    <c:forEach var="curso" items="${queryCursos.rows}">
                                        <option value="${curso.id_curso}"  ${curso.id_curso==row.id_curso?'selected':''}>${curso.nome_curso}- ${curso.codigo_curso}-V${curso.versao_curso} - ${curso.carga_horaria}h</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <p><label class="lbInput">Unidade<em>*</em></label>
                                <sql:query var="queryUnidade" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    SELECT  * FROM Unidades
                                </sql:query>
                                <select id="id_unidade" name="id_unidade" class="required" disabled>
                                    <option value="">Selecione um valor</option>
                                    <c:forEach var="unidade" items="${queryUnidade.rows}">
                                        <option value="${unidade.id_unidade}" ${unidade.id_unidade==row.id_unidade?'selected':''}>${unidade.desc_unidade}</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <p><label class="lbInput">Cidade<em>*</em></label>
                                <sql:query var="queryCidade" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    SELECT  * FROM Cidades
                                    order by nome_cidade
                                </sql:query>
                                <select name="id_cidade" class="required" disabled>
                                    <option value="">Selecione um valor</option>
                                    <c:forEach var="cidade" items="${queryCidade.rows}">
                                        <option value="${cidade.id_cidade}"  ${cidade.id_cidade==row.id_cidade?'selected':''} >${cidade.nome_cidade}</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <p><label class="lbInput">Turno<em>*</em></label>
                                <sql:query var="queryTurnos" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    select * from Turnos
                                    where situacao_turno='A'
                                </sql:query>
                                <select  name="id_turno" class="required" disabled>
                                    <option value="">Selecione um valor</option>
                                    <c:forEach var="turno" items="${queryTurnos.rows}">
                                        <option value="${turno.id_turno}" ${turno.id_turno==row.id_turno?'selected':''}>${turno.desc_turno}</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <p><label><span id="simbolo">+</span><a href="#" id="link_horarios">Horários Módulos</a></label>
                                <sql:query var="queryModulos" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    select * from modulos
                                    where id_curso=?
                                    <sql:param value="${row.id_curso}"/>
                                </sql:query>
                                <div id="horarios" >


                                    <c:forEach var="rowModulos" items="${queryModulos.rows}">
                                        <br>
                                        <input id="id_modulo" type="hidden" name="id_modulo" value="${rowModulos.id_modulo}">${rowModulos.desc_modulo}

                                        <table class="tablescroll" width="100%">
                                            <thead>
                                                <tr>
                                                    <th>Domingo</th>
                                                    <th>Segunda</th>
                                                    <th>Terça</th>
                                                    <th>Quarta</th>
                                                    <th>Quinta</th>
                                                    <th>Sexta</th>
                                                    <th>Sábado</th>
                                                </tr>
                                            </thead>

                                            <tr>
                                                <c:forEach var="dia" begin="1" end="7">
                                                    <td>
                                                        <sql:query var="queryHorarios" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                                            select horarios.*, dia from horarios
                                                            left join horarios_turmas
                                                            on horarios.id_horario=horarios_turmas.id_horario and dia=? and id_turma=? and id_modulo=?
                                                            where id_turno=?
                                                            order by hora_inicio
                                                            <sql:param value="${dia}"/>
                                                            <sql:param value="${row.id_turma}"/>
                                                            <sql:param value="${rowModulos.id_modulo}"/>
                                                            <sql:param value="${row.id_turno}"/>
                                                        </sql:query>
                                                        <c:forEach var="rowHorarios" items="${queryHorarios.rows}">
                                                            <input disabled type="checkbox" name="horarios"
                                                                   value="${rowModulos.id_modulo}_${rowHorarios.id_horario}_${dia}"
                                                                   ${rowHorarios.dia==dia?'checked':''}
                                                                   />
                                                            ${rowHorarios.hora_inicio} - ${rowHorarios.hora_fim}
                                                            <br>
                                                        </c:forEach>
                                                    </td>
                                                </c:forEach>
                                            </tr>
                                        </table>

                                        <br>
                                    </c:forEach>
                                </div>
                            </p>

                            <p><label class="lbInput">Período<em>*</em></label>
                                <fmt:formatDate var="data_inicio" value="${row.inicio_turma}" pattern="dd/MM/yyyy"/>
                                <fmt:formatDate var="data_fim" value="${row.fim_turma}" pattern="dd/MM/yyyy"/>

                                <input disabled type="text" id="data_inicio" name="data_inicio" value="${data_inicio}" size="12" maxlength="12" class="required">
                                <label>a</label>
                                <input disabled type="text" id="data_fim" name="data_fim" value="${data_fim}" size="12" maxlength="12" disabled>

                            </p>
                            <p><label class="lbInput">Código da Turma</label><i>Informe o código da turma vindo do GE</i>
                                <input disabled type="text" id="codigo_turma" name="codigo_turma" value="${row.codigo_turma}" size="12" maxlength="12">
                            </p>
                            <p><label class="lbInput">Número de alunos</label>
                                <input disabled type="text" id="alunos_turma" name="alunos_turma" size="12" maxlength="12" value="${row.alunos_turma}" >
                            </p>
                            <p><label class="lbInput">Cliente</label>
                                <input disabled type="text" id="cliente_turma" name="cliente_turma" size="60" maxlength="60" value="${row.cliente_turma}" >
                            </p>
                            <p><label class="lbInput">Gratuidade</label>
                                <label for="gratuita_turma">Sim</label><input disabled type="radio" id="gratuita_turma" name="gratuita_turma" value="S" ${row.gratuita_turma=='S'?'checked':''}>
                                <label for="gratuita_turma">Não</label><input disabled type="radio" id="gratuita_turma" name="gratuita_turma" value="N" ${row.gratuita_turma=='N'?'checked':''}>
                            </p>
                            <p>
                                <sql:query var="queryRegras" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    select *
                                    from regras
                                    order by desc_regra
                                </sql:query>
                                <label class="lbInput">Regra de alocação</label>
                                <select id="regra" name="id_regra" class="required" disabled>
                                    <option value="">Selecione um valor</option>
                                    <c:forEach var="regras" items="${queryRegras.rows}">
                                        <option value="${regras.id_regra}" ${regras.id_regra==row.id_regra?'selected':''}>${regras.desc_regra}</option>
                                    </c:forEach>
                                </select>

                            </p>
                            <br>

                        </c:forEach>

                        <div id="grade">
                            <table id="calendario"></table>
                            <div id="pager_calendario"></div>
                            <br>
                            <table id="list"></table>
                            <div id="pager"></div>
                            <br>
                            <table id="salas"></table>
                            <div id="pager_salas"></div>

                        </div>
                        <p id="salvar">                            
                            <input class="submit" type="button" id="consultar" name="consultar" value="Consultar" onclick="listar('fm_lista_turmas.jsp')">
                        </p>
                        <div id="ajax_dados" style="display:block">
                        </div>
                        <div id="msg" style="display:none"></div>
                    </fieldset>
                </div>
            <input type="hidden" id="token" name="token" value="${sessionScope.token}" /> </form>
        </div>
    </body>
    <script type="text/javascript">
        var lastsel2 ;
        var lastselsalas ;
        var lastselcal ;

        $(function(){
            $("#list").jqGrid({
                url:'fm_getGrade.jsp?token=${sessionScope.token}&id_turma=${param.chave}',
                datatype: 'xml',
                mtype: 'POST',
                colNames:[ 'Ordem','Módulo','Componente','C. Horária','Início','Fim','Sala','Sub-Turma','Copiar?'],
                colModel :[
                    {name:'ordem', index:'ordem', width:30, align:'center',edittype:"text",editable:true,sortable:false,editrules:{required:true}},
                    {name:'desc_modulo', index:'desc_modulo', width:90,edittype:"text",editable:false,sortable:false},
                    {name:'desc_componente', index:'desc_componente', width:180, align:'center',edittype:"text",editable:false,sortable:false},
                    {name:'carga_horaria', index:'carga_horaria', width:50, align:'center',edittype:"text",editable:true,sortable:false,editrules:{required:true}},
                    {name:'data_inicio', index:'data_inicio', width:50, align:'center',edittype:"text",editable:true,sortable:false,editrules:{required:true}},
                    {name:'data_fim', index:'data_fim', align:'center', width:50, edittype:"text",sortable:false,editable:true,editrules:{required:true}},
                    {name:'id_sala', index:'id_sala', align:'center', width:150, sortable:false,
                        editable:true,edittype:"select",
                        editoptions:{dataUrl:'../Alocacoes/fm_getSalas.jsp?token=${sessionScope.token}&id_unidade='+$("#id_unidade").val()},editrules:{required:true}
                    },
                    {name:'subturma', index:'subturma', width:30, align:'center',edittype:"text",editable:true,sortable:false},
                    {name:'copiar',index:'copiar',hidden:true,edittype:"checkbox",editable:true,sortable:false
                        ,editoptions: { value:"Sim:Nao" },editrules: {edithidden:true} },


                ],
                onSelectRow: function(id){
                    if(id && id!==lastsel2){
                        jQuery('#list').jqGrid('restoreRow',lastsel2);                      

                        lastsel2=id;
                    }
                    if(id == null) {
                        id=0;
                        if(jQuery("#salas").jqGrid('getGridParam','records') >0 )
                        {
                            jQuery("#salas").jqGrid('setGridParam',{url:"fm_getAlocacoesSalas.jsp?token=${sessionScope.token}&id="+id,page:1})
                            .trigger('reloadGrid');
                        }
                    } else {
                        jQuery("#salas").jqGrid('setGridParam',{url:"fm_getAlocacoesSalas.jsp?token=${sessionScope.token}&id="+id,page:1})
                        .trigger('reloadGrid');
                    }

                },
                pager: '#pager',
                autowidth: true,
                height: 200,
                rowNum:200,
                pgbuttons: false,
                pgtext: false,
                pginput:false,
                viewrecords: true,
                sortname: 'ordem',
                sortorder: 'desc',
                caption: 'Componentes'
            });

            jQuery("#list").jqGrid('navGrid','#pager', {add:false,edit:false,del:false,search:false}, //options
            {} // search options
        );

            $("#salas").jqGrid({
                url:'fm_getAlocacoesSalas.jsp?token=${sessionScope.token}&id=0',
                datatype: 'xml',
                mtype: 'POST',
                colNames:['Data', 'Hora Inicial','Hora Final','Sala','Sub-Turma','Situação','Otimizado'],
                colModel :[
                    {name:'data_alocacao', index:'data_alocacao', width:38,edittype:"text",editable:true,editrules:{required:true},editoptions:{size:12},sortable:false, align:"center"},
                    {name:'hora_inicio', index:'hora_inicio', width:30, align:'center',edittype:"text",editable:true,editrules:{required:true},sortable:false},
                    {name:'hora_fim', index:'hora_fim', width:30, align:'center',edittype:"text",editable:true,editrules:{required:true},sortable:false},
                    {name:'id_sala', index:'id_sala', align:'center', width:150, sortable:false,editoptions:{size:60},
                        editable:true,edittype:"select",
                        editoptions:{dataUrl:'../Alocacoes/fm_getSalas.jsp?token=${sessionScope.token}&id_unidade='+$("#id_unidade").val()},editrules:{required:true}
                    },
                    {name:'subturma', index:'subturma', width:20, align:'center',edittype:"text",editable:true,sortable:false},
                    {name:'situacao', index:'situacao', width:150, align:'center',edittype:"text",editable:false,sortable:false}
                    ,
                    {name:'otimizado', index:'otimizado', align:'center', width:20,
                        edittype:"select",editable:true,
                        editoptions: { value: "S:Sim;N:Não" } ,
                        sortable:false,editable:true },
                ],
                onSelectRow: function(id){
                    if(id && id!==lastselsalas){
                        jQuery('#salas').jqGrid('restoreRow',lastselsalas);
                        lastselsalas=id;
                    }
                },
                pager: '#pager_salas',
                autowidth: true,
                height: 200,
                rowNum:200,
                viewrecords: true,
                pgbuttons: false,
                pgtext: false,
                pginput:false,
                rownumbers: true,
                sortname: 'data_alocacao',
                sortorder: 'desc',
                caption: 'Salas e Horários'
            });

            jQuery("#salas").jqGrid('navGrid','#pager_salas', {search:false,edit:false,add:false,del:false}, //options
            {} // search options
        );



            $("#calendario").jqGrid({
                url:'fm_getCalendarioTurma.jsp?token=${sessionScope.token}&id_turma=${param.chave}',
                datatype: 'xml',
                mtype: 'POST',
                colNames:[ 'Dia','Executa?'],
                colModel :[
                    {name:'data_calendario', index:'data_calendario', width:50, align:'center',
                        edittype:"text",editable:true,sortable:false,editrules:{required:true}},
                    {name:'diautil_calendario', index:'diautil_calendario', width:20,align:'center',
                        edittype:"select",editable:true,sortable:false
                        ,editoptions: { value: "S:Sim;N:Não" } },
                ],
                onSelectRow: function(id){
                    if(id && id!==lastselcal){
                        jQuery('#calendario').jqGrid('restoreRow',lastselcal);
                        lastselcal=id;
                    }
                },
                pager: '#pager_calendario',
                width: 330,
                height: 100,
                rowNum:'auto',
                pgbuttons: false,
                pgtext: false,
                pginput:false,
                viewrecords: true,
                sortname: 'data_calandario',
                sortorder: 'desc',               
                caption: 'Calendário'
            });

            jQuery("#calendario").jqGrid('navGrid','#pager_calendario', {add:false,del:false,edit:false,search:false}, //options
            {} // search options
        );

        });

        function reloadGrid(id){
            jQuery("#salas").jqGrid('setGridParam',{url:"fm_getAlocacoesSalas.jsp?token=${sessionScope.token}&id="+id,page:1})
            .trigger('reloadGrid');
        }

    </script>
</html>
